import { useLookup } from '@/utils/hooks/useLookup';
import type { FormDataDto } from '@/api/avic/demo/DemoMainNestApi'; // 引入模块DTO
import {
  // getDemoMainNest,
  saveDemoMainNest,
  checkDemoUniqueUnique
} from '@/api/avic/demo/DemoMainNestApi'; // 引入模块API
import { createEditor } from '@wangeditor/editor'; // 引入富文本依赖
import { useRichText } from '@/utils/hooks/useRichText'; // 引入富文本相关配置及方法

export const emits = ['reloadData', 'close'];
export function useDemoMainNestForm({ props, emit }) {
  const { proxy } = getCurrentInstance();
  const form = ref<FormDataDto>({
    id: '',
    formStep1: {},
    formStep2: {},
    formStep3: {}
  });
  const demoMainNestStep1 = ref();
  const demoMainNestStep2 = ref();
  const demoMainNestStep3 = ref();
  const formRef = ref(null);
  const formStep1Ref = ref(null);
  const formStep2Ref = ref(null);
  const formStep3Ref = ref(null);
  const rulesStep1: Record<string, Rule[]> = {
    demoUserId: [{ required: true, message: '用户不能为空', trigger: 'change' }],
    secretLevel: [{ required: true, message: '密级不能为空', trigger: 'change' }]
  };
  const rulesStep2: Record<string, Rule[]> = {
    demoNotnull: [{ required: true, message: '必填不能为空', trigger: 'change' }]
  };
  const rulesStep3: Record<string, Rule[]> = {
    demoUnique: [
      { required: true, message: '唯一值不能为空', trigger: 'change' },
      { validator: (rule, value) => validateDemoUniqueUnique(rule, value), trigger: 'blur' }
    ]
  };
  const layout = {
    labelCol: { flex: '0 0 140px' },
    wrapperCol: { flex: '1 1 0' }
  };
  const colLayout = proxy.$colLayout2; // 调用布局公共方法
  const loading = ref(false);
  const uploadFile = ref(null); // 附件ref
  const autoCode = ref(null); // 自动编码ref
  const { lookupList } = useLookup(['PLATFORM_SEX', 'PLATFORM_CHECK_TYPE', 'PLATFORM_DEGREE']);
  const richtextDetail = ref(null); // 富文本ref
  const editorRef = shallowRef(null); // 编辑器实例，必须用 shallowRef
  const { toolbarConfig, editorConfig, onCreated, dealRichText, convertImageSrc } = useRichText(
    editorRef,
    'demoMainNestDemoRichtext',
    'DEMO_MAIN_NEST'
  );

  const currentStep = ref(0); // 当前向导步骤
  const steps = [
    { id: 'step1', title: '步骤一' },
    { id: 'step2', title: '步骤二' },
    { id: 'step3', title: '步骤三' }
  ];
  const stepDescribe = [
    '步骤一：创建采购订单首先选择采购类型，上传相应的采购依据附件',
    '步骤二：根据采购依据(请购单/采购计划)内容勾选相应需要采购的物料明细',
    '步骤三：为订单选择或填写合适的条款'
  ];

  onMounted(() => {
    if (props.formId) {
      // 编辑、详情页面加载数据
      getFormData(props.formId);
    }
  });
  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  });
  /**
   * 编辑、详情页面加载数据
   * @param {String} id 行数据的id
   */
  async function getFormData(id) {
    // 示例数据
    console.log('id', id);
    form.value.id = '111111';
    form.value.formStep1 = {
      demoUserId: '8a69ef448c325404018c32a5818b01c3',
      demoUserIdAlias: '多啦爱梦(undefined)',
      secretLevel: '1',
      demoRadio: '2',
      demoCheckbox: '1;2',
      demoRadioButton: '2',
      demoSelect: '001',
      demoSwitch: 'N'
    };
    form.value.formStep2 = {
      demoNotnull: 'gtest',
      demoCode: null
    };
    form.value.formStep3 = {
      demoUnique: 'test',
      demoRichtext: '<p>test</p>'
    };
    form.value.formStep1.demoCheckbox = form.value.formStep1.demoCheckbox?.toString()?.split(';'); // 处理复选框数据
    form.value.formStep1.demoSelectMultiple = form.value.formStep1.demoSelectMultiple?.toString()?.split(';'); // 处理多选下拉数据

    // 处理富文本
    await dealRichText(form.value.formStep3.demoRichtext);
    // 详情表单 富文本不可编辑
    if (richtextDetail.value !== null) {
      editorRef.value.disable();
    }

    // loading.value = true;
    // getDemoMainNest(id)
    //   .then(async (res) => {
    //     if (res.success) {
    //       form.value.id = res.data.id;
    //       form.value.formStep1 = res.data.formStep1;
    //       form.value.formStep2 = res.data.formStep2;
    //       form.value.formStep3 = res.data.formStep3;
    //       form.value.formStep1.demoCheckbox = form.value.formStep1.demoCheckbox?.toString()?.split(';'); // 处理复选框数据
    //       form.value.formStep1.demoSelectMultiple = form.value.formStep1.demoSelectMultiple?.toString()?.split(';'); // 处理多选下拉数据
    //       // 处理富文本
    //       await dealRichText(form.value.formStep3.demoRichtext);
    //       // 详情表单 富文本不可编辑
    //       if (richtextDetail.value !== null) {
    //         editorRef.value.disable();
    //       }
    //       loading.value = false;
    //     }
    //   })
    //   .catch(() => {
    //     proxy.$message.warning('获取表单数据失败！');
    //     loading.value = false;
    //   });
  }

  /** 保存 */
  function saveForm() {
    // case 1. 表单+表格
    // demoMainNestStep3.value.formStep3Ref.validate().then(() => { // 表单
    //   demoMainNestStep3.value.validate((validate) => { // 表格，行编辑表格校验方法需在最后一步vue文件中定义并暴露
    //     if (!validate) {
    //       return;
    //     }
    //     // 附件密级校验 先判断
    //     // ...
    //   });
    // });
    // case 2. 仅表格
    // demoMainNestStep3.value.validate((validate) => { // 行编辑表格校验方法需在最后一步vue文件中定义并暴露
    //   if (!validate) {
    //     return;
    //   }
    //   // 附件密级校验 先判断
    //   // ...
    // });
    // case 3. 仅表单
    demoMainNestStep3.value.formStep3Ref
      .validate()
      .then(() => {
        // 附件密级校验 先判断
        const errorMessage = demoMainNestStep3.value.uploadFile.validateUploaderFileSecret(form.value.formStep1.secretLevel);
        if (errorMessage) {
          return;
        }
        loading.value = true;
        const subInfoList = demoMainNestStep2.value.getChangedData(); // 获取子表数据
        // 处理数据
        const postData = proxy.$lodash.cloneDeep(form.value);
        postData.formStep1.demoCheckbox = postData.formStep1.demoCheckbox?.join(';'); // 处理复选框数据
        postData.formStep1.demoSelectMultiple = postData.formStep1.demoSelectMultiple?.join(';'); // 处理多选下拉数据
        postData.formStep1.demoSwitch = postData.formStep1.demoSwitch === 'Y' ? 'Y' : 'N'; // 处理开关
        postData.formStep2.demoSubNestList = subInfoList; // 挂载子表数据
        if (demoMainNestStep2.value.autoCode) {
          // 获取编码码段值
          postData.formStep2.demoCode = demoMainNestStep2.value.autoCode.getSegmentValue();
        }
        // 处理富文本
        const editorHtmljsonCopy = proxy.$lodash.cloneDeep(demoMainNestStep3.value.editorRef.children);
        convertImageSrc(editorHtmljsonCopy);
        const newEditor = createEditor({ content: editorHtmljsonCopy });
        const newEditorHtml = newEditor.getHtml();
        postData.formStep3.demoRichtext = newEditorHtml;
        // 发送请求
        saveDemoMainNest(postData)
          .then((res) => {
            if (res.success) {
              demoMainNestStep3.value.uploadFile.upload(form.value.id || res.data.formStep3); // 附件上传
            } else {
              loading.value = false;
            }
          })
          .catch(() => {
            loading.value = false;
          });
      })
      .catch((error) => {
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(demoMainNestStep3.value.formStep3Ref, error);
      });
  }
  /** 保存步骤一 */
  async function saveFormStep1() {
    let result = true;
    result = await demoMainNestStep1.value.formStep1Ref
      .validate()
      .then(() => {
        loading.value = true;
        // 处理数据
        const postData = proxy.$lodash.cloneDeep(form.value.formStep1);
        postData.demoCheckbox = postData.demoCheckbox?.join(';'); // 处理复选框数据
        postData.demoSelectMultiple = postData.demoSelectMultiple?.join(';'); // 处理多选下拉数据
        postData.demoSwitch = postData.demoSwitch === 'Y' ? 'Y' : 'N'; // 处理开关
        // 调用保存接口示例
        // saveDemoMainNest(postData)
        //   .then((res) => {
        //     if (res.success) {
        //       proxy.$message.success('保存成功！');
        //       return true;
        //     }
        //     proxy.$message.error('当前步骤保存失败！');
        //     loading.value = false;
        //     return false;
        //   })
        //   .catch(() => {
        //     loading.value = false;
        //     return false;
        //   });
        proxy.$message.success('保存成功！'); // 此行演示用，需删除
        loading.value = false; // 此行演示用，需删除
        return true; // 此行演示用，需删除
      })
      .catch((error) => {
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(demoMainNestStep1.value.formStep1Ref, error);
        return false;
      });
    return result;
  }
  /** 数据保存失败的回调 */
  function errorCallback() {
    loading.value = false;
  }
  /** 附件上传完之后的回调函数 */
  function afterUploadEvent(_successFile, errorFile) {
    if (errorFile.length > 0) {
      errorCallback();
      // 有附件保存失败的处理
      proxy.$message.error('附件保存失败！');
    } else {
      // 所有附件都保存成功的处理
      proxy.$message.success('保存成功！');
    }
    // 仅在最后一步才关闭弹窗
    if (currentStep.value === steps.length - 1) {
      emit('reloadData');
      emit('close');
    }
  }
  /** 异步校验唯一值唯一 */
  async function validateDemoUniqueUnique(_rule, value) {
    if (value) {
      const res = await checkDemoUniqueUnique({
        demoUnique: value,
        id: props.formId || ''
      });
      if (res.success) {
        if (res.data) {
          return Promise.resolve();
        }
        return Promise.reject('唯一值已存在!');
      }
      return Promise.reject('唯一值唯一性校验失败!');
    }
    return Promise.resolve();
  }
  /** 返回关闭事件 */
  function closeModal() {
    emit('close');
  }
  /** 刷新事件 */
  function reloadData() {
    emit('reloadData');
  }
  /** 步骤跳转 */
  async function onNextStep(step) {
    if (step > 1) {
      return;
    }
    let result = true; // 校验状态（校验失败时会置为false）

    // 步骤一：单独保存按钮 + 下一步并保存
    if (currentStep.value === 0 && step > 0) {
      result = await saveFormStep1();
    }

    // 步骤二： 仅下一步，无保存操作
    if (currentStep.value === 1 && step > 0) {
      // 子表数据校验
      demoMainNestStep2.value.validate((validate) => {
        if (!validate) {
          result = false;
        }
      });
      try {
        await demoMainNestStep2.value.formStep2Ref.validate();
      } catch (e) {
        result = false;
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(demoMainNestStep2.value.formStep2Ref, e);
      }
    }
    // 校验失败
    if (!result) return;
    currentStep.value += step;
  }
  return {
    proxy,
    currentStep,
    steps,
    stepDescribe,
    form,
    formRef,
    formStep1Ref,
    formStep2Ref,
    formStep3Ref,
    rulesStep1,
    rulesStep2,
    rulesStep3,
    layout,
    colLayout,
    loading,
    lookupList,
    uploadFile,
    afterUploadEvent,
    autoCode,
    richtextDetail,
    toolbarConfig,
    editorConfig,
    editorRef,
    onCreated,
    saveForm,
    saveFormStep1,
    closeModal,
    reloadData,
    onNextStep,
    demoMainNestStep1,
    demoMainNestStep2,
    demoMainNestStep3
  };
}
